package me.zhengjie.modules.banner.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import me.zhengjie.base.PageInfo;
import me.zhengjie.base.QueryHelpMybatisPlus;
import me.zhengjie.base.impl.CommonServiceImpl;
import me.zhengjie.config.FileProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.service.mapper.LocalStorageMapper;
import me.zhengjie.utils.ConvertUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.banner.domain.Banner;
import me.zhengjie.modules.banner.service.BannerService;
import me.zhengjie.modules.banner.service.dto.BannerDto;
import me.zhengjie.modules.banner.service.dto.BannerQueryParam;
import me.zhengjie.modules.banner.service.mapper.BannerMapper;
import me.zhengjie.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
* @author TianI
* @date 2022-02-07
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = BannerService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class BannerServiceImpl extends CommonServiceImpl<BannerMapper, Banner> implements BannerService {
    private final FileProperties properties;
    // private final RedisUtils redisUtils;
    private final BannerMapper bannerMapper;
    private final LocalStorageMapper localStorageMapper;

    @Override
    public PageInfo<BannerDto> queryAll(BannerQueryParam query, Pageable pageable) {
        IPage<Banner> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<Banner> page = bannerMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, BannerDto.class);
    }

    @Override
    public List<BannerDto> queryAll(BannerQueryParam query){
        return ConvertUtil.convertList(bannerMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), BannerDto.class);
    }

    @Override
    public Banner getById(Long id) {
        return bannerMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public BannerDto findById(Long id) {
        return ConvertUtil.convert(getById(id), BannerDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(BannerDto resources) {
        Banner entity = ConvertUtil.convert(resources, Banner.class);
        return bannerMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(BannerDto resources){
        Banner entity = ConvertUtil.convert(resources, Banner.class);
        int ret = bannerMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Long> ids){
        // delCaches(ids);
        return bannerMapper.deleteBatchIds(ids);
    }

    @Override
    public Banner create(Long companyId, MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            Banner banner1 = bannerMapper.selectOne(new QueryWrapper<Banner>().eq("banner_url", file.getName()));
            if (banner1!=null){
                return null;
            }else {
                Banner banner = new Banner();
                banner.setBannerUrl(file.getName());
                banner.setCompanyId(companyId);
                bannerMapper.insert(banner);
                return banner;
            }

        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }

    @Override
    public List<Banner> getBanner(Long companyId) {
        List<Banner> banners = bannerMapper.selectList(new QueryWrapper<Banner>().eq("company_id", companyId));
        return banners;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id){
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<BannerDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (BannerDto banner : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("轮播图路径", banner.getBannerUrl());
              map.put("创建时间", banner.getCreateTime());
              map.put("更新时间", banner.getUpdateTime());
              map.put("关联总公司id", banner.getCompanyId());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
